package com.wlstock.funi.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.android.volley.Request.Method;
import com.android.volley.VolleyError;
import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.constant.URLConstant;
import com.wlstock.funi.dao.SelfFundDao;
import com.wlstock.funi.model.SelfFundModel;
import com.wlstock.funi.request.CustomStringRequest;
import com.wlstock.funi.request.EventBusConstants;
import com.wlstock.funi.request.NetWorkListener;
import com.wlstock.funi.utils.CaculateUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.StockUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Stack;

/**
 * 1秒到2秒执行1次，用来进行一些队列任务
 * @author admin
 *
 */
public class MissionService extends Service implements NetWorkListener {
	
	private static final String MA10 = "10";

	private static final String MA5 = "5";

	private static final String SCALE60 = "60";

	private MissionServiceBinder myBinder = new MissionServiceBinder();
	
	private List<String> myStockList;
	private List<SelfFundModel> fundModels;

	private Stack<SelfFundModel> missionStack;
	private SelfFundModel curSeFundModel;

//	private CustomStringRequest req;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		
		
	}
	
	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		
		myStockList = SelfFundDao.getInstance(this).queryAllSelfFundStkNos();
		fundModels  = SelfFundDao.getInstance(this).queryAllSelfFundModes();
		
		if (missionStack == null) {
			missionStack = new Stack<SelfFundModel>();	
		}
		
		if (fundModels != null) {
			if (missionStack.size() == 0) {
				//每次任务是否为0，如果为0把所有的内容放进去
				for(int i = 0 ; i < fundModels.size(); i++){
					missionStack.add(fundModels.get(i));
				}
			}else{
				//每次pop出最上面的一个,直到最后的size为0
				SelfFundModel sfModel = missionStack.peek();
				if (curSeFundModel == null) {
					curSeFundModel = sfModel;
					missionStack.pop();
					queryLatestMission(curSeFundModel);
				}
			}	
		}
	}

	private void queryLatestMission(SelfFundModel pop) {
		// TODO 监控60分钟均线等
		reqMA5(pop);
	}

	private void reqMA5(SelfFundModel pop) {
		CustomStringRequest req = new CustomStringRequest();
		req.networkResponseListener = this;
		int scale = 60;
		int ma5 = 5;
		req.request(Method.GET, URLConstant.SINA_HOST,null , null, minKReq(pop,scale,ma5,10), pop.getStockNo()+"_"+scale +"_"+ma5);
	}
	
	private void reqMA10(SelfFundModel pop) {
		CustomStringRequest req = new CustomStringRequest();
		req.networkResponseListener = this;
		int scale = 60;
		int ma5 = 10;
		req.request(Method.GET, URLConstant.SINA_HOST,null , null, minKReq(pop,scale,ma5,10), pop.getStockNo()+"_"+scale +"_"+ma5);
		
	}
	
	/**
	 * 获取分钟线的url,例如60分钟5个周期取10个
	 * @param sfModel 
	 * @param scale 多少分钟，只能传入5，10，30，60
	 * @param ma    周期，只能传入5，10，20
	 * @param len   数据长度
	 * @return
	 */
	private String minKReq(SelfFundModel sfModel, int scale,int ma, int len) {
		// TODO 获取分钟线的url
//		http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sh600030&scale=60&ma=5&datalen=10
		StringBuffer sb = new StringBuffer("http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?");
		sb.append("&symbol=").append(StockUtils.parsetStkCode2ZB(sfModel.getStockNo())+sfModel.getStockNo()).append("&scale=").append(scale).append("&ma=").append(ma).append("&datalen=").append(len);
		return sb.toString();
	}
	
	
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return myBinder ;
	}
	
	
	public class MissionServiceBinder extends Binder {

		public MissionService getService() {
			return MissionService.this;
		}
	}


	@Override
	public void onErrorResponse(VolleyError error, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onErrorResponse(VolleyError error, String eventCode) {
		// TODO Auto-generated method stub
		if (SCALE60.equals(eventCode)) {
			curSeFundModel = null;
		}
	}

	@Override
	public void onResponse(String response, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onResponse(String response, String eventCode) {
		// TODO Auto-generated method stub
//		ToastUtils.showMiddleMsg(this, "Update MD Price Success");
		FundAsyTask<String, Void, Void> task = new FundAsyTask<String, Void, Void>();
		task.backListener = new TaskLitener<String, Void>() {

			@Override
			public Void doInBackground(String... params) {
				String[] components = params[1].split("_");
				if (components!=null && components.length == 2) {
					String stkNo = components[0];
					String scale = components[1];			
					String ma = components[2];
					if (SCALE60.equals(scale)) {
						try {
							JSONArray arr = new JSONArray(params[0]);
							JSONObject lastObject = arr.getJSONObject(arr.length()-1);
							float open = Float.valueOf(lastObject.optString("open"));
							float high = Float.valueOf(lastObject.optString("high"));
							float low  = Float.valueOf(lastObject.optString("low"));
							float close = Float.valueOf(lastObject.optString("close"));
							if (lastObject.has("ma_price"+ma)) {
								float ma_price = Float.valueOf(lastObject.optString("ma_price"+ma));
//								SelfFundModel sfModel = SelfFundDao.getInstance(MissionService.this).querySelfFundModel(stkNo);
								if (curSeFundModel!=null && stkNo.equals(curSeFundModel.getStockNo())) {
									if (open>ma_price && CaculateUtils.getFloatDis(high, close)>3 && (CaculateUtils.getFloatDis(low, open)<-2 && CaculateUtils.getFloatDis(close, ma_price)<-0.5)) {
										String title = curSeFundModel.getStockName()+"冲高回落，现在"+ma+"日均线下";
										String content = curSeFundModel.getStockName()+"("+curSeFundModel.getStockNo()+")"+"高位回落:"+CaculateUtils.getFloatDis(high, close)+"%";
										NotiUtils.showSimpleNoti(MissionService.this, NotiIdGenerator.generate(curSeFundModel.getStockNo(), NotiIdGenerator.GenerFrom.MDPARSER),title ,content, R.drawable.ic_ai);
										FundApplication.getInstance().playSoundPool(NotiIdGenerator.getNotiRingRaw(NotiIdGenerator.GenerFrom.MDPARSER));
									}
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
						
						if (MA5.equals(ma)) {
							reqMA10(curSeFundModel);
						}else if (MA10.equals(ma)) {
							curSeFundModel = null;
						}
					}
				}
				return null;
			}
		};
		task.execute(response, eventCode);
	}
	
}
